package com.sky.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sky.constant.MessageConstant;
import com.sky.dto.UserLoginDTO;
import com.sky.entity.User;
import com.sky.exception.LoginFailedException;
import com.sky.mapper.UserMapper;
import com.sky.properties.WeChatProperties;
import com.sky.service.UserService;
import com.sky.utils.HttpClientUtil;
import org.apache.http.impl.client.HttpClients;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 老杨
 * @version 1.0
 */
@Service
public class UserServiceImpl implements UserService {

    private static final String WX_LOGIN= "https://api.weixin.qq.com/sns/jscode2session";

    @Autowired
    WeChatProperties weChatProperties;
    @Autowired
    UserMapper userMapper;

    @Override
    public User wxLogin(UserLoginDTO userLoginDTO) {
        //使用 微信接口 获取 openId
        String openid = getOpenid(userLoginDTO);

        //判断 是否 openId 是否为 null ,为null 抛出登录异常
        if (openid == null){
            throw new LoginFailedException(MessageConstant.LOGIN_FAILED);
        }

        //不为null 进行判断是否 为新用户,如果是新用户 就进行注册
        User user = userMapper.getUserByOpenid(openid);
        if (user == null){
            //构建 User 对象，并进行注册
          user =  User.builder()
                            .openid(openid)
                            .createTime(LocalDateTime.now()).build();
            userMapper.registered(user);
        }

        //不管是否存在 该用户 ，最后都会返回user对象
        return user;
    }

    //通过 码 获取 openId
    public String getOpenid(UserLoginDTO userLoginDTO){
        //使用 微信接口 获取 openId
        Map<String, String> paramMap = new HashMap();
        paramMap.put("appid", weChatProperties.getAppid());
        paramMap.put("secret",weChatProperties.getSecret());
        paramMap.put("js_code",userLoginDTO.getCode());
        paramMap.put("grant_type","authorization_code");
        //返回 json 格式数据
        String json = HttpClientUtil.doGet(WX_LOGIN, paramMap);
        //解析json 格式数据
        JSONObject jsonObject = JSON.parseObject(json);
        //拿到openid
       String openid =(String) jsonObject.get("openid");
       return openid;
    }
}
